package org.leetcode.middle.leetcode24;



public class Solution
{


    public ListNode swapPairs5(ListNode head){
        if (head==null || head.next==null){
            return null;
        }

        ListNode one = head;
        ListNode two = head.next;
        ListNode three = two.next;

        two.next=one;

        one.next=swapPairs5(three);

        return two;
    }

    /**
     * 第二次编写
     * @param head
     * @return
     */
    public ListNode swapPairs4(ListNode head){

        if (head==null || head.next==null)
        {
            return head;
        }

        ListNode one = head;
        ListNode two = head.next;
        ListNode three =two.next;


        two.next=one;
        one.next= swapPairs4(three);;

        return two;
    }


    public ListNode swapPairs(ListNode head)
    {
        if (head==null|| head.next==null )
        {
            return head;
        }

        ListNode pointerOne = head.next;

        head.next=swapPairs(pointerOne.next);

        pointerOne.next=head;

       return pointerOne;
    }

    public ListNode swapPairs3(ListNode head)
    {
        if (head==null || head.next==null )
        {
            return head;
        }
        ListNode one = head;
        ListNode two = head.next;
        ListNode three = two.next;

        one.next=swapPairs3(three);
        two.next=one;

        return two;
    }



    /**
     * 官方题解
     * @param head
     * @return
     */
    public ListNode swapPairs2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = head.next;
        head.next = swapPairs2(newHead.next);
        newHead.next = head;
        return newHead;
    }


    //遍历输出列表
    public void loop(ListNode node)
    {
        while (node!=null)
        {
            System.out.println(node.val);
            node = node.next;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        ListNode listNode = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, null))));

        ListNode swapPairs = solution.swapPairs4(listNode);

        solution.loop(swapPairs);
    }

}
